package com.lebang.controller.sys;

import com.alibaba.fastjson.JSONObject;
import com.lebang.common.Login;
import com.lebang.common.validcode.ValidCodeStatus;
import com.lebang.common.validcode.ValidCodeUtil;
import com.lebang.component.RedisClient;
import com.lebang.domain.LogoutRecord;
import com.lebang.entity.member.LbbMember;
import com.lebang.example.LogoutRecordExample;
import com.lebang.model.enums.buss.UserStatus;
import com.lebang.service.LogoutRecordService;
import com.lebang.service.SysCommonService;
import com.lebang.service.buss.MemberService;
import com.lebangweb.common.TextUtil;
import com.lebangweb.common.UUIDUtil;
import com.lebangweb.response.Callback;
import com.lebangweb.response.JsonData;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import static com.lebang.common.validcode.RedisLock.LOCKPHONECODE;


/**
 * 注销审核
 *
 * @author xwj
 * @date 2020-06-17
 */
@Controller
@RequestMapping("/sys/logoutrecord")
public class LogoutRecordController {
    @Autowired
    private LogoutRecordService baseService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private SysCommonService commonService;
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private ValidCodeUtil validCodeUtil;

    @Login
    @GetMapping("/list")
    public String list() {
        return "/logoutrecord/list";
    }

    @Login
    @GetMapping("/add")
    public String add(Long id, Model model) {
        LogoutRecord vo;
        if (id != null) {
            vo = baseService.selectById(id);
        } else {
            vo = new LogoutRecord();
        }
        model.addAttribute("item", vo);
        return "/logoutrecord/edit";
    }

    @Login
    @PostMapping("/edit")
    @ResponseBody
    public JsonData edit(LogoutRecord vo) {
        if (vo.getId() != null) {
            vo.setModifyTime(LocalDateTime.now());
            baseService.updateById(vo);
        } else {
            vo.setCreateTime(LocalDateTime.now());
            vo.setHasDeleted(0);
            baseService.insertModel(vo);
        }
        return Callback.success("success", "修改成功");
    }

    @Login
    @PostMapping("/sure")
    @ResponseBody
    public JsonData sure(Long id) {
        baseService.updateStatueById(2,id);
        LogoutRecord record = baseService.selectOneById(id);
        LbbMember member = memberService.selectMemberById(record.getMemberId());
        try {
            String phone = member.getPhone();
            //加锁防止重复发
            String uuid = UUIDUtil.M();
            boolean a = redisClient.tryGetDistributedLock(LOCKPHONECODE.getName() + phone, uuid, 3000);
            if (a) {
                ValidCodeStatus validCode = validCodeUtil.getLogoutSuccess(phone);
                if (validCode.isStatus()) {
                    //return Callback.success("success", "发送成功", "");
                } else {
                    return Callback.fail("error",  validCode.getMsg(), null);
                }
            } else {
                return Callback.fail("error", "请勿重复操作哦");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Callback.fail("error", e.getMessage());
        }
        return Callback.success("success", "审核通过");
    }

    @Login
    @PostMapping("/back")
    @ResponseBody
    public JsonData back(Long id) {
        baseService.updateStatueById(1,id);
        LogoutRecord record = baseService.selectOneById(id);
        LbbMember member = memberService.selectMemberById(record.getMemberId());
        member.setStatus(UserStatus.Allow.name());
        memberService.updateMemberById(member);
        return Callback.success("success", "审核不通过");
    }


    @Login
    @PostMapping("/delete")
    @ResponseBody
    public JsonData delete(Long id) {
        baseService.deleteById(id);
        return Callback.success("success", "删除成功");
    }

    @Login
    @ApiOperation(value = "分页")
    @PostMapping("/list")
    @ResponseBody
    public JSONObject list(HttpServletRequest request, @RequestParam Integer page, @RequestParam Integer limit) {
        LogoutRecordExample example = new LogoutRecordExample();
        example.setOffset((page - 1) * limit.longValue());
        example.setLimit(limit);
        LogoutRecordExample.Criteria criteria = example.createCriteria();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("data", baseService.selectByExample(example));
        jsonObject.put("count", baseService.countByExample(example));
        return jsonObject;
    }




    @Login
    @RequestMapping(value = ("/data"), method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> datalist(HttpServletRequest request, HttpServletResponse response) {

        Map<String, Object> list = new HashMap<>();
        /**
         * 参数列表
         * */
        Map<String, Object> paramsMap = queryParameter(request);
        paramsMap.put("orderBy","order by create_time desc");

        int pageSize = Integer.parseInt(String.valueOf(paramsMap.get("limit")));
        int page = Integer.parseInt(String.valueOf(paramsMap.get("page")));
        int startNum = (page - 1) * pageSize;
        String table = (String) paramsMap.get("table");
        Map<String, String> queryMap = (Map<String, String>) paramsMap.get("query");
        Map<String, String> timeMap = (Map<String, String>) paramsMap.get("time");
        Map<String, String> searchMap = (Map<String, String>) paramsMap.get("key");
        String orderBy = paramsMap.get("orderBy") == null ? "" : paramsMap.get("orderBy").toString();

        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("data", commonService.listByQuery(table, pageSize, startNum, queryMap, timeMap, searchMap, orderBy));
        returnMap.put("count", commonService.countByQuery(table, queryMap, timeMap, searchMap));
        returnMap.put("code", 0);
        return returnMap;
    }

    public Map<String, Object> queryParameter(HttpServletRequest request) {
        /**
         * 主要的查询参数，包含
         * limit 每页数量
         * page  当前页
         * table 表名
         * query 查询的字段名称和值
         * time  查询的时间段
         * */
        Map<String, Object> resultMap = new HashMap<>();

        /**
         * 获取and 的查询条件
         * */
        Map<String, String> queryMap = new HashMap<>();
        /**
         * 获取时间的查询条件，针对于修改做操作 和修改时间做比较
         * */
        Map<String, Object> timeMap = new HashMap<>();

        /**
         *  获取查询检索条件，or
         * */
        Map<String, String> searchMap = new HashMap<>();


        Map<String, String[]> paramMap = request.getParameterMap();
        Iterator<String> iterator = paramMap.keySet().iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            String[] val = paramMap.get(key);
            if (val != null && val.length > 0) {
                String value = val[0].trim();
                if (!TextUtil.isEmpty(key, value)) {
                    String str = "";
                    if (key.contains("query")) {
                        String name = key.substring(key.indexOf("[") + 1, key.indexOf("]"));
                        queryMap.put(name, value);
                    } else if (key.contains("time")) {
                        String name = key.substring(key.indexOf("[") + 1, key.indexOf("]"));
/*                        if("end".equals(name)){
                            value= this.getNowAfter(value);
                        }*/
                        timeMap.put(name, value);
                    } else if (key.contains("key")) {
                        String name = key.substring(key.indexOf("[") + 1, key.indexOf("]"));
                        String[] names = name.split("[,]");
                        for (String string : names) {
                            searchMap.put(string, value);
                        }
                    } else {
                        resultMap.put(key, value);
                    }
                }
            }
        }

        resultMap.put("query", queryMap);
        resultMap.put("time", timeMap);
        resultMap.put("key", searchMap);
        return resultMap;
    }


}
